<template>
  <div>
    <consoleFloor title="喷淋设置">
      <div class="card-conent">
        <div style="padding:20px 0;display: flex;justify-content: space-between;">
          <div>
            <span class="title">自动喷淋</span>
            <el-switch :loading="loading1" :before-change="beforeChange1" v-model="value1" @change="changeSwitc(value1,0)"/>
          </div>
        </div>
        <div class="formbox">
          <el-form :model="formInline.result" :inline="true" ref="resultDom" label-width="100px">
            <el-form-item label="pm2.5限值:">
              <el-input size="small" @blur="clickAuto('pm2.5')" v-model="formInline.result['pm2.5'] " :disabled="!value1">
                <template #append>ug/m3</template></el-input>
            </el-form-item>
            <el-form-item label="pm10限值:">
              <el-input size="small" @blur="clickAuto('pm10')" v-model="formInline.result['pm10']" :disabled="!value1">
                <template #append>ug/m3</template></el-input>
            </el-form-item>
            <el-form-item label="温度限值:">
              <el-input size="small" @blur="clickAuto('heat')" v-model="formInline.result['heat']" :disabled="!value1">
                <template #append>℃</template></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="card-conent">
        <foldOpen :foldopt="{ isOpen:value2, isButton:false }" ref="childFn">
            <template #header>
              <div style="padding:20px 0;display: flex;justify-content: space-between;">
                <div>
                  <span class="title">定时喷淋</span>
                  <el-switch :loading="loading2" :before-change="beforeChange2" v-model="value2" @change="changeSwitc(value2,1)"/>
                </div>
                <el-button style="margin-left:30px" size="small" @click="clickAddTime">新增</el-button>
              </div>
            </template>
            <template #content>
                <itable :table="constfig.tableConfig" :tableData="constfig.tableData" :page-bean="constfig.pageBean" @pageChange="tablePage">
                  <template #cronstime="prop">
                    <span>{{ proxy.$moment(prop.obj.row.cronstime).format('HH:mm:ss') }}</span>
                  </template>
                  <template #status="props">
                    <el-button type="text" :style="{color:props.obj.row.jobstatus == 0 ? '#F56C6C' : '#409EFF'}">{{ props.obj.row.jobstatus == 0 ? '关闭' : '开启' }}</el-button>
                  </template>
                  <template #freq="prop">
                    <span>{{ filtFreq(prop.obj.row.freq) }}</span>
                  </template>
                  <template #jurisdiction="props">
                    <el-button type="text" style="{color:#409EFF}" @click="tableEdit(props.obj.row)"><el-icon><EditPen /></el-icon>编辑</el-button>
                    <el-button type="text" :disabled="props.obj.row.jobstatus == 0 ? false : true" @click="clickON(props.obj.row)">开启</el-button>
                    <el-button type="text" style="{color:#409EFF}" :disabled="props.obj.row.jobstatus == 0 ? true : false" @click="clickOFF(props.obj.row)">关闭</el-button>
                  </template>
                </itable>
            </template>
        </foldOpen>
      </div>
    </consoleFloor>
    <el-card class="box-card" style="margin-top:10px">
      <template #header>
        <h1>喷淋记录(最近{{ allData.length }}次)</h1>
      </template>
      <itable :table="tconfig.tableConfig" :tableData="tconfig.tableData" :page-bean="tconfig.pageBean" @pageChange="pageChange">
        <template #costtime="props">
          {{ turnTime(props.obj.row.costtime) }}
        </template>
      </itable>
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      :title="activeNames ? '新增' : '编辑'"
      width="40%"
    >
      <el-form :model="timeForm" class="timeForm" label-width="80px"  ref="ruleForm" :rules="rules" >
        <div style="display:flex;">
          <el-form-item label="喷淋设备" prop="deviceid">
              <el-select v-model="timeForm.deviceid" class="m-2" clearable :disabled="!activeNames" placeholder="请选择喷淋设备" size="small">
                <el-option v-for="item in deviceList" :key="item.iotcode" :label="item.devicename" :value="item.iotcode" />
              </el-select>
          </el-form-item>
          <el-form-item label="持续时间" prop="keeptime">
              <el-select v-model="timeForm.keeptime" class="m-2" clearable placeholder="请选择持续时间" size="small">
                <el-option v-for="item in keeptimeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
          </el-form-item>
        </div>
        <div style="display:flex;">
          <el-form-item label="频次" prop="frequency">
              <el-select v-model="timeForm.frequency" multiple class="m-2 frequency" clearable placeholder="请选择频次" size="small">
                <el-option v-for="item in frequencyLsit" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
          </el-form-item>
          <el-form-item label="时间点" prop="time">
              <el-time-picker v-model="timeForm.time" clearable class="datePicker" size="small" arrow-control placeholder="请选择时间点" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCanel">取消</el-button>
          <el-button type="primary" @click="onSubmit('ruleForm')">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
<div>
</div>
</template>

<script setup lang='ts'>
import { reactive, ref, toRefs } from 'vue';
import itable from '@/components/table/table.vue'
import { PageBean } from "@/utils/page-bean";
import useCurrentInstance from '@/utils/useCurrentInstance';
import { timeToCron } from '@/utils/utils'
import consoleFloor from '@/components/consoleFloor/index.vue'
import { useGetters } from '@/store/hooks'
import foldOpen from '@/components/foldOpen.vue/index.vue'

const { projectInfo } = toRefs(useGetters(["projectInfo"],'')) as {projectInfo:any}
let value1 = ref(false)
let value2 = ref(false)
let loading1 = ref(false)
let loading2 = ref(false)
let dialogVisible = ref(false)
const activeNames = ref(true)
const ruleForm = ref()
let rowData = ref()
let deviceList = ref([]) as any
let allData = ref([])

const { proxy } = useCurrentInstance()
let frequencyLsit = ref([
  { value: 'mon', label: '周一', cron: 2 },
  { value: 'tue', label: '周二', cron: 3  },
  { value: 'wed', label: '周三', cron: 4  },
  { value: 'thu', label: '周四', cron: 5  },
  { value: 'fri', label: '周五', cron: 6  },
  { value: 'sat', label: '周六', cron: 7  },
  { value: 'sun', label: '周日', cron: 1  },
])
let keeptimeList = ref([
  {value:'10分钟',label:'10分钟'},
  {value:'20分钟',label:'20分钟'},
  {value:'30分钟',label:'30分钟'},
  {value:'40分钟',label:'40分钟'},
  {value:'50分钟',label:'50分钟'},
  {value:'1小时',label:'1小时'},
  {value:'2小时',label:'两小时'},
])
const rules = ref({
  time: [
    { required: true, message: '请选择时间点', trigger: 'blur' }
  ],
  frequency: [
    { required: true, message: '请选择频率', trigger: 'blur' }
  ],
  keeptime: [
    { required: true, message: '请选择持续时间', trigger: 'blur' }
  ],
  deviceid: [
    { required: true, message: '请选择喷淋设备', trigger: 'blur' }
  ],
})
let param = reactive({
  jobid: null,
  projectid: projectInfo.value.deptId,
  deviceid: "",
  devicetype: "spray",
  freq: "",
  keeptime: "",
  cronstime: "",
  onoff: 1,
  jobstatus:1,
  cronexpress:"",
  methodparams:''
})
interface form {
  result:object|string,
  id?:number | string | null,
  projectid?:number | string,
  deviceid?:number | null,
  status?:string,
  type?:string
}
interface timeFace {
  time: string,
  frequency: Array<string|number>,
  keeptime:string,
  deviceid:string
}
let formInline:form = reactive({
  id:null,
  projectid:'',
  status:'',
  type:'spray',
  result:{'pm2.5': 0, 'pm10': 0, 'heat': 0}
})
let timeForm:timeFace = reactive({
  time: '',
  frequency: [],
  keeptime:'',
  deviceid:''
})
// 定时喷淋
const constfig = reactive({
  tableConfig: {} as {loading:boolean,[propName:string]:any},
  tableData: [] as any[],
  pageBean: new PageBean(10, 1, 0),
})
// 喷淋日志
const tconfig = reactive({
  tableConfig: {} as {loading:boolean,[propName:string]:any},
  tableData: [] as any[],
  pageBean: new PageBean(8, 1, 0),
})

// 接口-查询喷淋设备列表
const getSprayDevice = () => {
  proxy.$api.getSprayDevice({ datatype: 0, projectid: projectInfo.value.deptId, type: 'spray' }).then(res => {
    deviceList.value = res.data
  })
}
getSprayDevice()

// 接口-定时喷淋列表
const getTimeDevice = () => {
  constfig.tableConfig.loading = true
  proxy.$api.getTimeDevice({ projectid: projectInfo.value.deptId, type: "spray"}).then(res => {
    constfig.tableData = res.data
    let ifshow:Array<number> = []
    res.data.map((item,index) => {
      if(item.jobstatus == 1){
        ifshow.push(index)
      }
    })
    ifshow.length!==0 ? value2.value = true :  ''
    constfig.tableConfig.loading = false
  })
}
getTimeDevice()

// 接口-查询喷淋日志记录
const getSprayData = () => {
  tconfig.tableConfig.loading = true
  proxy.$api.getSprayData({projectid:projectInfo.value.deptId}).then(res => {
    allData.value = res.data
    tconfig.tableData = allData.value.slice(0,tconfig.pageBean.pageSize)
    tconfig.pageBean.Total = allData.value.length
    tconfig.tableConfig.loading = false
  })
}
getSprayData()
// 接口-查询自动喷淋
const getSavelogAuto = () => {
  proxy.$api.getSavelogAuto({projectid:projectInfo.value.deptId,type: "spray"}).then(res => {
    if(res.data){
      res.data.result = eval(`(${res.data.result})`)
      for(let key in formInline){
        formInline[key] = res.data[key]
      }
      formInline.type = 'spray'
      value1.value = formInline.status == 'off' ? false : true
    }
  })
}
getSavelogAuto()


// 接口-自动喷淋新增/编辑
const addSavelogAuto = () => {
  formInline.result = JSON.stringify(formInline.result)
  if(formInline.projectid == projectInfo.value.deptId){
    formInline.projectid = formInline.projectid
  }else{
    formInline.projectid = projectInfo.value.deptId
    formInline.id = null
  }
  proxy.$api.addSavelogAuto(formInline).then(res => {
    if(res.code == 0){
      getSavelogAuto()
    }else{
      proxy.$message.error(res.msg)
    }
  }).catch(err => { console.log(err) })
}

interface ChildInstance {
	clickOpenHidden: () => void
}
const childFn = ref<ChildInstance>()
// 接口-定时喷淋新增
const getsaveOrEditCron = (data) => {
  proxy.$api.getsaveCron(data).then(res => {
    if(res.code == 0){
      getTimeDevice()
      proxy.$message.success('新增成功')
      childFn.value?.clickOpenHidden()
    }else{
      proxy.$message.success(res.msg)
    }
  }).catch(err => console.log(err) )
}
// 接口-定时喷淋修改
const getModiyCron = (data) => {
  proxy.$api.getModiyCron(data).then(res => {
    if(res.code == 0){
      getTimeDevice()
      proxy.$message.success('修改成功')
      childFn.value?.clickOpenHidden()
    }else{
      proxy.$message.success(res.msg)
    }
  }).catch(err => console.log(err) )
}
// 接口-定时喷淋关
const getChangeStatus = (bool:number,id:string) => {
  proxy.$api.getChangeStatus({status:bool,ids:id}).then(res => {
    if(res.code == 0){
      getTimeDevice()
    }
  })
}

// 自动喷淋表单提交
const clickAuto = async(val) => {
    let num = formInline.result[val]
    if(num.match(/[^0-9\.]|(\.(?=.*\.))|^\.|^\d*\.\d*\./g) == null && num){
      addSavelogAuto()
    }else{
      proxy.$message.warning(val+'输入框填写不符合规则')
      getSavelogAuto()
    }
}
// 喷淋开关
const changeSwitc = (value, type) => {
  if(type == 0){
    // 自动开关
    formInline.status = value == 0 ? 'off' : 'on'
    value == 0 ? getForceclose() : null
    addSavelogAuto()
  }else{
    // 定时开关
    timecFun(value)
  }
  if(value){
    if(type == 0){
      value2.value = !value
      timecFun(!value)
    }else{
      value1.value = !value
      formInline.status = !value ? 'on' : 'off'
      addSavelogAuto()
    }
  }
}
// 喷淋强制关闭
const getForceclose = () => {
  proxy.$api.getForceclose({projectid: formInline.projectid,type: formInline.type})
}
const timecFun = (value) => {
  let arr = JSON.parse(JSON.stringify(constfig.tableData)),data:Array<object|number> = []
  arr.map(item => {
    data.push(item.jobid,item.sonid)
  })
  getChangeStatus(value ? 1 : 0, data.join())
}
// 定时喷淋单开
const clickON = (id) => {
  getChangeStatus(1,`${id.jobid},${id.sonid}`)
}
// 定时喷淋单关
const clickOFF = (id) => {
  getChangeStatus(0,`${id.jobid},${id.sonid}`)
}
// 定时喷淋编辑
const tableEdit = (row) => {
  rowData.value = row
  timeForm.deviceid = row.deviceid
  timeForm.time = row.cronstime
  timeForm.frequency = row.freq.split(',')
  timeForm.keeptime = row.keeptime
  activeNames.value = false
  dialogVisible.value = true
}
// 定时喷淋新增
const clickAddTime = () => {
  timeForm.deviceid = ''
  activeNames.value = true
  dialogVisible.value = true
  setTimeout(() => {
    ruleForm.value.resetFields()
  }, 100);
}
// 提交表单
const onSubmit = async(formEl) => {
  if (!formEl) return
  await ruleForm.value.validate((valid: Boolean, fields: object) => {
    if (valid) {
      let date = timeForm.keeptime.indexOf('分钟') !== -1 ? Number(timeForm.keeptime.split('分')[0]) : Number(timeForm.keeptime.split('小')[0])
      param.cronstime = proxy.$moment(timeForm.time).format('YYYY-MM-DD HH:mm:ss')
      let cronetime = proxy.$moment(timeForm.time).add(date, date >= 10 ? 'm' : 'h').format('YYYY-MM-DD HH:mm:ss')
      param.freq = (timeForm.frequency).join()
      param.keeptime = timeForm.keeptime
      param.deviceid = timeForm.deviceid
      param.methodparams = ((Math.random()*1000+100) + 1).toFixed(0)
      let w = [] as Array<number|string>
      frequencyLsit.value.map(itme => {
        timeForm.frequency.map(item2 =>{
          if(itme.value == item2){
            w.push(itme.cron)
          }
        })
      })
      param.cronexpress = timeToCron({loopType:'WEEKLY',effectTime:new Date(param.cronstime),wloopValue:w})
      param.onoff = 1
      let on = param
      let off = JSON.parse(JSON.stringify(param))
      off.methodparams = ((Math.random()*2000+100) + 2).toFixed(0)
      off.onoff = 0
      off.cronexpress = timeToCron({loopType:'WEEKLY',effectTime:new Date(cronetime),wloopValue:w})
      if(activeNames.value){
        param.jobid = null
        param.projectid = projectInfo.value.deptId
        getsaveOrEditCron({ondata:on,offdata:off})
      }else{
        on.jobid = rowData.value.jobid
        off.jobid = rowData.value.sonid
        delete on.methodparams
        delete off.methodparams
        param.projectid = rowData.value.projectid
        getModiyCron({ondata:on,offdata:off})
      }
      dialogVisible.value = false
    }
  })
}
// 取消提交
const onCanel = () => {
  ruleForm.value.resetFields()
  dialogVisible.value = false
}
// 分页
const tablePage = () => {

}
const pageChange = () => {
  tconfig.tableData = allData.value.slice(tconfig.pageBean.pageSize * (tconfig.pageBean.pageIndex - 1),tconfig.pageBean.pageSize * tconfig.pageBean.pageIndex)
}
// 初始化表格
const initTable = () => {
  // 定时喷淋
  constfig.tableConfig = {
    loading: false,
    hasSelect: false,
    hasIndex: true,
    hasOperation: false,
    hasSearch: false,
    hasPage: false,
    tr: [
      {
        label: "时间点",
        minWidth: "140",
        prop: "cronstime",
        show:'template'
      },
      {
        label: "频次",
        minWidth: "110",
        prop: "freq",
        show:'template'
      },
      {
        label: "持续时间",
        minWidth: "160",
        prop: "keeptime",
      },
      {
        label: "状态",
        minWidth: "100",
        prop: "status",
        show:'template'
      },
      {
        label: "操作",
        minWidth: "100",
        prop: "jurisdiction",
        show:'template'
      }
    ]
  }
  // 喷淋记录
  tconfig.tableConfig = {
    loading: true,
    hasSelect: false,
    hasIndex: true,
    hasOperation: false,
    hasSearch: false,
    hasPage: true,
    tr: [
      {
        label: "时间",
        minWidth: "140",
        prop: "currenttime",
      },
      {
        label: "持续时长",
        minWidth: "110",
        prop: "costtime",
        show:'template'
      },
      {
        label: "触发原因",
        minWidth: "160",
        prop: "onreason",
      },
      {
        label: "水量(t)",
        minWidth: "100",
        prop: "watermeter",
      }
    ]
  }
}
initTable()
const turnTime = (time) => {
  if(time){
    const duration = proxy.$moment.duration(time, 'seconds');
    if (duration.asHours() >= 1) {
      return duration.asHours().toFixed(2) + ' h'
    } else {
      return duration.asMinutes().toFixed(2) + ' min'
    }
  }else{
    return '-'
  }
}
const filtFreq = (type) => {
  if(type){
    let data = type.split(',')
    let arr = filt(data)
    return arr.join() ? arr.join() : type
  }else{
    return type
  }
}
const filt = (data,arr:Array<string>=[]) => {
 frequencyLsit.value.map(item => {
      data.map(item2 => {
        if(item.value == item2){
          arr.push(item.label)
        }
      })
  })
  return arr
}

const beforeChange1 = () => {
  loading1.value = true
  return new Promise((resolve) => {
    setTimeout(() => {
      loading1.value = false
      return resolve(true)
    }, 500)
  })
}
const beforeChange2 = () => {
  loading2.value = true
  return new Promise((resolve) => {
    setTimeout(() => {
      loading2.value = false
      return resolve(true)
    }, 500)
  })
}
</script>

<style lang='scss' scoped>
.formbox {
  width: 100%;

  .el-form {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
  }
}

.card-conent {
  border-bottom: 1px solid #EBEBEB;
  margin-bottom: 10px;
}

.title {
  margin-right: 10px;
  font-size: 15px;
  font-weight: bold;
  color: rgb(121, 121, 121);
}

.timeForm {
  width: 100% !important;
  .el-form-item{
    width: 50%;
  }
  .el-select--small{
    width: 90%;
  }
  :deep(.el-date-editor.el-input){
    width:90%;
  }
}
.dialog-footer{
  width: 100%;
  display: flex;
  justify-content: center;
}
</style>
